package com.cloud.server.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.common.core.base.ApiResponseEnum;
import com.cloud.common.core.base.enums.ApiBaseEnum;
import com.cloud.common.core.exception.BizException;
import com.cloud.common.core.util.BeanCopyUtil;
import com.cloud.server.system.dto.QueryUserDTO;
import com.cloud.server.system.dto.UserInputDTO;
import com.cloud.server.system.mapper.entity.SystemUser;
import com.cloud.server.system.mapper.UserMapper;
import com.cloud.server.system.mapper.entity.UserRole;
import com.cloud.server.system.service.IUserRoleService;
import com.cloud.server.system.service.IUserService;
import com.cloud.server.system.util.PageUtil;
import com.cloud.server.system.vo.SystemUserVO;
import com.google.common.base.Function;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;

/**
 * 用户表 服务实现类
 *
 * @author zhangxun
 * @since 2020-08-24
 */
@Service
@Slf4j
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, SystemUser> implements IUserService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private IUserRoleService userRoleService;

    @Override
    public Map<String, Object> listUser(QueryUserDTO queryUserDTO) {
        Page<SystemUserVO> page = new Page<>(queryUserDTO.getPageNum(), queryUserDTO.getPageSize());
        Map<String, Object> pageData = PageUtil.toPage(this.baseMapper.listUser(page, queryUserDTO));
        return pageData;
    }

    @Override
    @Transactional
    public boolean addUser(UserInputDTO userInputDTO) {
        SystemUser user = BeanCopyUtil.copy(SystemUser.class, userInputDTO);
        user.setCreateTime(LocalDateTime.now());
        user.setAvatar(SystemUser.DEFAULT_AVATAR);
        user.setPassword(passwordEncoder.encode(SystemUser.DEFAULT_PASSWORD));
        int row = this.baseMapper.insert(user);
        if (0 == row){
            log.info("添加用户失败！user:", JSONObject.toJSON(user));
            throw new BizException(ApiResponseEnum.FAIL,"系统错误，添加失败");
        }
        String[] roles = user.getRoleId().split(StringPool.COMMA);
        setUserRoles(user, roles);
        return true;
    }

    @Override
    @Transactional
    public boolean editUser(SystemUser user) {
        // 更新用户
        user.setModifyTime(LocalDateTime.now());
        int row = this.baseMapper.updateById(user);
        if (0 == row){
            log.info("编辑用户失败！user:", JSONObject.toJSON(user));
            throw new BizException(ApiResponseEnum.FAIL,"系统错误，编辑失败");
        }

        boolean success = userRoleService.remove(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, user.getUserId()));
        String[] roles = user.getRoleId().split(StringPool.COMMA);
        setUserRoles(user, roles);
        return true;
    }

    @Override
    public SystemUser findByUserId(Long userId) {
        if (null == userId){
            throw  new BizException(ApiResponseEnum.PARAMETER_CAN_NOT_NULL,"用户id不能为空！");
        }

        SystemUser user = this.baseMapper.selectById(userId);
        if (null == user){
            throw  new BizException(ApiResponseEnum.DATA_NULL,"数据不存在！");
        }
        return this.baseMapper.selectById(userId);
    }

    @Override
    @Transactional
    public ApiBaseEnum deleteByUserIds(String[] userIds) {
        if (ArrayUtil.isEmpty(userIds)){
            throw  new BizException(ApiResponseEnum.PARAMETER_CAN_NOT_NULL,"用户id不能为空！");
        }
        this.baseMapper.deleteBatchIds(Arrays.asList(userIds));
        // 删除用户角色
        this.userRoleService.deleteUserRolesByUserId(userIds);
        return ApiResponseEnum.SUCCESS;
    }

    private void setUserRoles(SystemUser user, String[] roles) {
        Arrays.stream(roles).forEach(roleId -> {
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getUserId());
            userRole.setRoleId(Long.valueOf(roleId));
            userRoleService.save(userRole);
        });
    }
}
